import { toRefs } from 'vue'
import { useMapStore } from '@/stores/map' // 使用pinia
import { useWuyeStore } from '@/stores/wuye'
import { useDialogsStore } from '@/stores/dialogs' // 使用pinia

export default function useBuffer() {
  const { map } = toRefs(useMapStore())
  const { wuye } = toRefs(useWuyeStore())
  const { dialogs } = useDialogsStore()
  function getBuffer() {
    /* 1. 创建画布 (空的矢量数据源) */
    var source = new ol.source.Vector({})
    var layer = new ol.layer.Vector({ source })
    layer.setStyle(
      new ol.style.Style({
        //填充色
        fill: new ol.style.Fill({
          color: 'rgba(255, 76, 88, 0.5)',
        }),
        //边线颜色
        stroke: new ol.style.Stroke({
          color: '#ff5354',
          width: 2,
        }),
      })
    )
    map.value.addLayer(layer)
    /* 2. 创建画笔 */
    var draw = new ol.interaction.Draw({
      /* 画布在什么地方绘制 */
      source,
      type: 'LineString',
    })
    draw.on('drawend', function (evt) {
      console.log('end', evt.feature.getGeometry())
      console.log(evt.feature.getGeometry().getCoordinates())
      /* 创建缓冲数据 */
      var line = turf.lineString(evt.feature.getGeometry().getCoordinates())
      var buffered = turf.buffer(line, 0.2, { units: 'kilometers' })
      //创建数据geojson对象和数据源对象
      var format = new ol.format.GeoJSON()
      /* ol对象转geojson对象 */
      var b = format.readFeature(buffered)
      console.log(b.getGeometry()) // 形状
      //将数据添加数据源的
      source.addFeature(b)

      //添加图层
      Query.queryByGeom({
        geometry: b.getGeometry(),
        service: {
          name: 'guanggu',
          layerId: 0,
        },
        callback: (res) => {
          // map.value.removeInteraction(draw)
          map.value.getInteractions().pop() //移除绘制图形
          console.log(res)
          dialogs.notice.add = true
          let data = res.SFEleArray.map((item) => {
            return { name: item.AttValue[3], tel: item.AttValue[4] }
          })
          wuye.value = data
        },
      })
    })
    /* 3. 将画笔添加到地图容器 */
    map.value.addInteraction(draw)
  }
  return {
    getBuffer,
  }
}
